<!-- oem登录页 -->
<template>
  <div class="oemLogin-view">
    <div class="oemLogin-main">
      <Vcode
        :show="isShow"
        @success="success"
        @close="close"
      />
        <div class="oemLogin-title">
          <div class="title-left">
            <img :src="oemConfig.logoUrl" alt="">
            <!-- <span >页面名称页面名称页面</span> -->
          </div>
          <div class="title-right">
            <el-dropdown @command="handleCommand">
              <el-button >
                {{language}}<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command= '中文(简体)'>中文(简体)</el-dropdown-item>
                <!-- <el-dropdown-item command= '中文(繁体)'>中文(繁体)</el-dropdown-item> -->
              </el-dropdown-menu>
            </el-dropdown>
            <!-- 富文本 -->
            <div class="title-tag" v-html="oemConfig.titleBarInfo">

            </div>
            <!-- <div  v-for="(item, index) in oemConfig.titleBarList" @click="open(item.jumpLink)" :key="index" >{{item.custom}}</div> -->
          </div>
        </div>
        <div class="login-form">
          <el-form class="m7-form" ref="loginForm" :model="form" :rules="rules" label-width="0px">
            <p class="text-login">登录</p>
            <el-form-item label="" prop="loginName">
              <el-input
                class="input"
                v-model.trim="form.loginName"
                placeholder="请输入账号"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="" prop="password">
              <el-input
                class="input"
                v-model.trim="form.password"
                type="password"
                @keyup.enter.native="loginSubmit"
                autocomplete="off"
                placeholder="请输入密码"
                clearable
              ></el-input>
            </el-form-item>
          </el-form>
          <div class="status-box">
            <el-checkbox v-model="form.remember">记住密码</el-checkbox>
            <span @click.stop="showDropdown" class="status-config">状态设置</span>
            <LoginDropdown
              ref="loginDropdownRef"
              @changeWebchatLoginStatus="changeWebchatLoginStatus"
              @change-login-status="changeLoginStatus"
              @change-login-type="changeLoginType"
            >
            </LoginDropdown>
          </div>
          <div class="submit" :class="loginLoading?'loading-circle-wrap':''" @click.stop="loginSubmit">
            <span>{{loginLoading?'登录中':'登录'}}</span>
            <span class="loading-circle">
              <i></i>
              <i></i>
              <i></i>
            </span>
          </div>

          <div v-html="oemConfig.privacyProtocolInfo" class="concent">

          </div>
        </div>
        <!-- 页脚 -->
        <div class="oemLogin-bottom" v-html="oemConfig.pageFootInfo">

        </div>
    <BindPhone
      @bindPhoneSuccess="bindPhoneSuccess"
      ref="bindPhoneRef"
    ></BindPhone>
    </div>
  </div>
</template>

<script lang='ts'>
import { Component, Vue } from 'vue-property-decorator'
import LoginDropdown from '../LoginDropdown.vue'
import BindPhone from '../BindPhone.vue'
import I18nSelect from '../I18nSelect.vue'
import Vcode from 'vue-puzzle-vcode'
import { OemModule } from '@/store/modules/oem'
import { CommonModule } from '@/store/modules/common'
import { LoginModule } from '@/store/modules/login/index'
import { deepClone } from '@/utils/common'
import router from '@/router/handleRoute'
import { PermissionModule } from '@/store/modules/permission'
@Component({ name: 'OemIndex', components: { I18nSelect, LoginDropdown, BindPhone, Vcode } })
export default class OemIndex extends Vue {
  public $store: any
  public $router: any
  public $message: any
  private loginLoading: boolean = false
  public form: any = {
    loginName: '',
    password: '',
    remember: true,
    policy: false,
    loginStatus: true,
    loginType: 'WEBRTC'
  }

  public language = '中文(简体)'

  public mounted () {
    const privacyClick: any = document.querySelector('#privacyClick')
    if (privacyClick) {
      privacyClick.addEventListener('click', () => {
        const parent = privacyClick.parentNode
        parent.classList.toggle('is-checked')
      })
    }
    if (this.form.policy && privacyClick) {
      privacyClick.parentNode.classList.add('is-checked')
    }
  }

  get oemConfig () {
    return this.$store.state.oem.oemConfig
  }

  private showDropdown () {
    (this as any).$refs.loginDropdownRef.open()
  }

  private bindPhoneSuccess () { // 绑定手机号成功
    this.loginSubmit()
  }

  public jinx = '<label data-v-1e6160cc=""  class="el-checkbox policy-checkbox-wrap is-checked"><span  class="el-checkbox__input"><span id=\'privacyClick\' class="el-checkbox__inner"></span><input type="checkbox" aria-hidden="false" class="el-checkbox__original" value=""></span><span class="el-checkbox__label"><span data-v-1e6160cc=""> 我已阅读并同意 <a data-v-1e6160cc="" href="//m.7moor.com/static/m7ServiceTerms.html" target="_blank">《服务协议》</a>和<a data-v-1e6160cc="" href="//m.7moor.com/static/m7PrivacyPolicy.html" target="_blank">《隐私政策》</a></span><!----></span></label>'
  private webchatStatus = true
  private changeWebchatLoginStatus (type: boolean) {
    this.webchatStatus = type
  }

  private changeLoginStatus (status: boolean) {
    this.form.loginStatus = status
  }

  private changeLoginType (type: string) {
    this.form.loginType = type
  }

  public handleCommand (val) {
    this.language = val
  }

  public isShow = OemModule.oemConfig.biometricVerificationStatus === 1
  public success () {
    this.isShow = false
  }

  public close () {
    //
  }

  get getPlatformConfig () {
    const initConfig = this.$store.state.common.initConfig
    const platformConfig = initConfig ? initConfig.platformConfig : {}
    return platformConfig
  }

  private loginSubmit () {
    if (this.loginLoading) {
      return false
    }
    const privacyClick: any = document.querySelector('#privacyClick')?.parentNode
    if (privacyClick) {
      if (!privacyClick.classList.contains('is-checked')) {
        this.$message.error('请阅读并同意相关协议')
        return
      } else {
        this.form.policy = true
      }
    }
    (this as any).$refs.loginForm.validate((valid) => {
      if (valid) {
        const platformConfig = this.getPlatformConfig
        // if (!this.form.policy && platformConfig && platformConfig.m7ServiceTerms && platformConfig.m7PrivacyPolicy) { // 没勾选协议 && 不是oem && 不是私云 && 有配置协议url
        //   this.$message.error('请阅读并同意《服务协议》和《隐私政策》')
        //   return
        // }
        const value = window.localStorage.getItem('loginForm')
        let temp = { loginName: '', password: '', remember: true, policy: false, loginStatus: true, loginType: 'WEBRTC' }
        if (value && value !== 'undefined' && value !== 'null') {
          temp = JSON.parse(value)
        }
        let encrypted = ''
        if (this.form.password === temp.password) { // 取的缓存密码
          encrypted = this.form.password
        }
        const loginData = {
          form: deepClone(this.form),
          encrypted,
          isLogin: true,
          isConnectSocket: true,
          isConnectWebRtc: true,
          webchatStatus: { status: this.webchatStatus ? 'open' : 'close', _id: '' },
          domain: window.location.href.split('/')[2]
        }
        this.loginLoading = true
        LoginModule.SignIn(loginData).then((loginRes: any) => {
          if (loginRes && loginRes.success) {
            const commonAppIdList = ['knowledge_mgt', 'call_task', 'robot', 'sms']
            const publicCache = this.$store.state.common.publicCache || null
            const list = (publicCache && publicCache.commonAppIdList.map(item => item.id)) || [] // 常用应用列表
            const roleList = [...loginRes.data.user.limits]
            PermissionModule.GenerateRoutes(roleList)
            // 设置动态路由
            router.addRoutes(PermissionModule.routes)
            commonAppIdList.forEach(item => {
              if (item === 'call_task' && roleList.includes('call_task')) { // 有预览外呼的权限
                if (!(list.includes('my_call_task_list') || list.includes('my_auto_call_task_list') || list.includes('auto_call_task_list') || list.includes('preview_dialout_list'))) {
                  // 我的预览外呼 || 我的自动外呼 || 预览外呼管理 || 自动外呼管理  都没有设置为常用，要把一级菜单的预览外呼剔除
                  PermissionModule.delRoutes('call_task')
                  CommonModule.updateLoginMenuList({ menu: 'call_task', type: 'delete' })
                }
              } else if (!(roleList.includes(item) && list.includes(item))) {
                if (roleList.includes(item)) {
                  PermissionModule.delRoutes(item)
                }
              }
            })
            this.$router.push({ path: (publicCache && publicCache.loginMenuList[0]) || 'home/index' }) // 登录之后，push当前有权限的一级菜单第一个
          } else if (loginRes.code === '2013') { // 手机模式登录，没有手机号要绑定手机号
            (this as any).$refs.bindPhoneRef.open(loginRes.sessionId)
          }
          this.loginLoading = false
        }).catch(() => {
          this.loginLoading = false
        })
      } else {
        console.log('error submit!!')
        return false
      }
    })
  }

  public open (url) {
    // console.log(url)
    window.open('http://' + url)
  }

  private getLocalFrom () {
    const value = window.localStorage.getItem('loginForm')
    let localForm = this.form
    if (value && value !== 'undefined' && value !== 'null') {
      localForm = JSON.parse(value)
    }
    return localForm
  }

  private currentYear: number = 2020
  private rules: object = {
    loginName: [{ required: true, message: '请输入账号', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
  }

  private beforeMount () {
    window.sessionStorage.clear() // 每次到登录页，清除session的缓存
    this.currentYear = new Date().getFullYear()
    this.form = this.getLocalFrom()
    document.title = this.oemConfig.pageName
    const link: any = document.querySelector('link[rel*="icon"]')
    link.href = this.oemConfig.labelPictureUrl
    // document.getElementsByTagName('head')[0].appendChild(link);

    console.log(link)
  }
}
</script>
<style lang='stylus' scoped>
.oemLogin-view
  width 100%
  height 100%
  overflow auto
.oemLogin-main
  width 100%
  height 100%
  background #F8F9FC
  position relative
  min-height 800px
.oemLogin-title
  background #fff
  width 100%
  height 80px
  margin-bottom 100px
  padding 0px 20px
  display flex
  justify-content: space-between;
  .title-left
    display flex
    align-items center
    height 80px
    img
      height: 50px;
      border-radius: 4px;
      display inline-block
      margin-right 260px
      object-fit: cover
    span
      height: 16px;
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: 600;
      color: #191D3A;
      display inline-block
  .title-right
    height 80px
    display flex
    align-items center
    flex-direction: row-reverse;
    flex 1
    .title-tag
      margin-right 50px
      overflow: hidden;
      height 24px
      line-height 24px!important
      text-overflow:ellipsis;
      // white-space: nowrap;
      display flex
      text-align center
.login-form
  margin 0 auto
  width: 380px
  height: 506px
  background: #FFFFFF
  border-radius: 10px
  padding 40px
.oemLogin-bottom
  position absolute
  bottom 10px
  width 100%
  text-align center
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
  display: -webkit-box;
.submit
    height 46px
    margin-top 73px
    margin-bottom 14px
    border-radius 3px
    text-align center
    font-size 14px
    line-height 46px
    font-weight bold
    color #fff
    background-color $c-main
    cursor pointer
/deep/.input
  .el-input__inner
    height 46px
    margin-top 20px
    font-size 14px
  .el-input__suffix
    top 12px
.text-login
  margin-top 10px
  font-size: 26px;
  font-family: PingFang SC;
  font-weight: 600;
  color: #303753;
  line-height: 25px;
.el-form-item
  margin-bottom 0
.status-box
  margin-top 22px
  position relative
  display flex
  justify-content: space-between;
  align-content: center;
  .status-config
    font-size 14px
    height 20px
    line-height 20px
    cursor pointer
    color $c-main
.concent
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  font-size 14px
  overflow: hidden;
/deep/.el-checkbox__label
  font-size 14px
/deep/.title-tag>p
  line-height 24px
.loading-circle i
  top 19px
</style>
<style scoped>
@media screen and (max-height: 800px) {
   .login-form{
     height:440px;
   }
  .submit {
    margin-top: 23px;
  }
}
</style>
